package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @param req
     * @return
     */
    @PostMapping("/login")
    public R<String>  login(@RequestBody User user, HttpServletRequest req){
        LambdaQueryWrapper<User> lqw =new LambdaQueryWrapper<User>();
        lqw.eq(User::getPhone,user.getPhone());
        User users = userService.getOne(lqw);
        if (users==null) {
             userService.save(user);
        }
        User users2 = userService.getOne(lqw);
        req.getSession().setAttribute("user",users2.getId());
        log.info("session={}", users2.getId());
        return R.success("登录成功");
    }

    /**
     * 退出登录
     * @param req
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest req){
         req.getSession().removeAttribute("user");
        return R.success("退出登录");
    }

}
